package com.fernfx.xingtan.common.base;


import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.fernfx.xingtan.Constant;
import com.fernfx.xingtan.ConsumerApplication;
import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.AppManager;
import com.fernfx.xingtan.common.entity.user.MemberEntity;
import com.fernfx.xingtan.main.ui.MainActivity;
import com.fernfx.xingtan.user.AccountManager;
import com.fernfx.xingtan.utils.CollectionUtil;
import com.fernfx.xingtan.utils.LogUtils;
import com.fernfx.xingtan.utils.OtherUtil;
import com.fernfx.xingtan.utils.SoftInputUtil;
import com.fernfx.xingtan.utils.ToastUtil;
import com.fernfx.xingtan.view.dialog.LoadingDialog;

import java.util.Map;

import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;


/**
 * BaseActivity
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected Activity mContext;
    protected Toolbar mToolbar;
    protected AppBarLayout mAppBarLayout;
    private Fragment mFragment;
    protected Map<String, Object> requestArgsMap = Constant.RequestArgs.REQUEST_ARGS_MAP;
    private long exitTime = 0;

    public BaseActivity(){
        AppManager.getAppManager().addActivity(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;

        onBeforeSetContentLayout();
        setContentView(getLayoutResId());
        onAfterSetContentLayout(savedInstanceState);

        initButterKnife();
        initToolbar();
        initView();
        initData();
        initListener();
    }

    protected void addFragment(int frameLayoutId, Fragment fragment) {
        if (fragment != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (fragment.isAdded()) {
                if (null == mFragment) {
                    transaction.show(fragment).commitAllowingStateLoss();
                } else {
                    transaction.hide(mFragment).show(fragment).commitAllowingStateLoss();
                }
            } else {
                if (null != mFragment) {
                    transaction.hide(mFragment).add(frameLayoutId, fragment).commitAllowingStateLoss();
                } else {
                    transaction.add(frameLayoutId, fragment).commitAllowingStateLoss();
                }
            }
            mFragment = fragment;
        }
    }

    protected void onBeforeSetContentLayout() {
    }

    protected void onAfterSetContentLayout(Bundle savedInstanceState) {
    }

    protected abstract int getLayoutResId();

    private void initToolbar() {
        int id = getAppBarLayoutResId();
        mAppBarLayout = (AppBarLayout) findViewById(getAppBarLayoutResId());
        mToolbar = (Toolbar) findViewById(getToolbarResId());
        if (null != mToolbar) {
            mToolbar.setTitle("");
            mToolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.black));
            setSupportActionBar(mToolbar);
        }
        setShowHomeUp(true);
    }

    /**
     * init view
     */
    protected void initView() {
    }

    /*
     *init butterKnife
     */
    protected void initButterKnife() {
        ButterKnife.bind(this);
    }

    protected void initListener() {
        if (null != mAppBarLayout) {
            mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    canShowRefreshIcon(verticalOffset >= 0);
                }
            });
        }
    }

    protected void initData() {
    }

    protected int getToolbarResId() {
        return R.id.toolbar;
    }

    protected int getTitleViewId() {
        return R.id.tv_common_title;
    }

    protected int getAppBarLayoutResId() {
        return 0;
    }

    protected void canShowRefreshIcon(boolean shown) {
    }


    /**
     * 显示或隐藏返回箭头按键
     */
    protected void setShowHomeUp(boolean showHomeUp) {
        ActionBar bar = getSupportActionBar();
        if (null != bar) {
            bar.setDisplayHomeAsUpEnabled(showHomeUp);
        }
    }

    /**
     * 设置标题
     */
    public void setToolbarTitle(CharSequence title) {
        ActionBar bar = getSupportActionBar();
        if (null != bar) {
            bar.setTitle("");
        }

        // 设置toolbar中的标题
        TextView tvTitle = ((TextView) findViewById(getTitleViewId()));
        if (null != tvTitle) {
            tvTitle.setText(title);
        }
    }

    protected void onBack() {
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home: {
                //检查键盘如果打开则关闭
                SoftInputUtil.hideKeyboard((BaseActivity) mContext);

                finish();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && ConsumerApplication.TOUCH_EXIT_MAP.containsKey(OtherUtil.getClassSimpleName(mContext.getClass()))
                && ConsumerApplication.TOUCH_EXIT_MAP.get(OtherUtil.getClassSimpleName(mContext.getClass()))){
            if ((System.currentTimeMillis() - exitTime) > 2500) {
                //弹出提示，可以有多种方式
                ToastUtil.showBottomtoast(R.string.exit_application);
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getAppManager().finishAllActivity();
                System.exit(0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        hideLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!CollectionUtil.isEmpty(requestArgsMap)) {
            requestArgsMap.clear();
        }
    }

    public String trimEditText(EditText editText) {
        if (editText == null) {
            return "";
        }
        return editText.getText().toString().trim();
    }

    /*
     * true 去除空格
     */
    public String trimEditText(EditText editText,boolean flag) {
        if (editText == null) {
            return "";
        }
        if (!flag) {
            return trimEditText(editText);
        }
        return editText.getText().toString().trim().replaceAll(" ","");
    }

    public String trimTextView(TextView textView) {
        if (null == textView) {
            return "";
        }
        return textView.getText().toString().trim();
    }

    public void showLoading() {
        LoadingDialog.show(this);
    }

    public void hideLoading() {
        LoadingDialog.hide(this);
    }

    protected <T extends View> T find(int id) {
        return findViewById(id);
    }
}